<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="客户名称" prop="customerId">
      <el-select
        v-model="formData.customerId"
        filterable
        remote
        reserve-keyword
        placeholder="请输入客户名称搜索"
        remote-show-suffix
        :remote-method="remoteMethod"
        :loading="loading"
        style="width: 240px"
        @change="customerChange"
      >
        <el-option
          v-for="item in options"
          :key="item.id"
          :label="item.customerName"
          :value="item.id"
        />
      </el-select>

      </el-form-item>

      
      <el-form-item label="船公司代码" prop="priceId">
        <el-select
        v-model="formData.priceId"
        filterable
        remote
        placeholder="请输入船公司代码"
        remote-show-suffix
        :remote-method="searchShipCompany"
        :loading="loading"
        style="width: 240px"
        @change="shipCompanyChange" >
        <el-option
          v-for="item in shipCompanyOptions"
          :key="item.id"
          :label="item.companyCode"
          :value="item.id"
        >
          <span style="float: left;padding-right:20px">{{ item.companyCode }}</span>
            <span
              style="
                float: left;
                color: var(--el-text-color-secondary);
                font-size: 13px;">
               柜型-{{ item.containerType }}    (费用- {{item.shipFee}}/{{item.dockFee}})
            </span>

        </el-option>
      </el-select>

      </el-form-item>

      <el-form-item label="账单日期" prop="billDate">
        <el-date-picker
          v-model="formData.billDate"
          type="date"

          value-format="YYYY-MM-DD"
          placeholder="选择日期"
        />
      </el-form-item>

      <el-form-item label="订单号" prop="orderNo">
        <el-input v-model="formData.orderNo" placeholder="请输入订单号" />
      </el-form-item>

      <!-- <el-form-item label="船公司名称" prop="companyName">
        <el-input v-model="formData.companyName" placeholder="请输入船公司名称" />
      </el-form-item> -->
     
      <el-form-item label="柜型" prop="containerType">
        <el-select v-model="formData.containerType" placeholder="请选择柜型">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.SHIP_CONTAINER_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="柜型数量" prop="containerCount" >
        <el-input v-model="formData.containerCount" placeholder="请输入柜型数量" @input="containerCountInput" />
      </el-form-item>
      <el-form-item label="船公司费(单价)" prop="shipFee" >
        <el-input v-model="formData.shipFeeUnit" placeholder="请输入船公司费" @input="containerCountInput" />
      </el-form-item>
      <el-form-item label="码头费用(单价)" prop="dockFee">
        <el-input v-model="formData.dockFeeUnit" placeholder="请输入码头费用"  @input="containerCountInput" />
      </el-form-item>
      <el-form-item label="手续费(单价)" prop="serviceFee">
        <el-input v-model="formData.serviceFeeUnit" placeholder="请输入手续费" @input="containerCountInput" />
      </el-form-item>
      
      <el-form-item label="总费用" prop="totalFee">
        <el-input v-model="formData.totalFee" placeholder="请输入总费用" />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>

      <!-- <el-form-item label="账单状态" prop="billStatus">
        <el-select v-model="formData.billStatus" placeholder="请选择账单状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CUSTOMER_BILL_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="支付日期" prop="payTime">
        <el-date-picker
          v-model="formData.payTime"
          type="date"
          value-format="x"
          placeholder="选择支付日期"
        />
      </el-form-item> -->
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { CustomerBillApi, CustomerBillVO } from '@/api/crm/customerbill'
import { CustomerApi, CustomerVO } from '@/api/crm/customer'

import { PriceTemplateApi, PriceTemplateVO } from '@/api/crm/pricetemplate'

/** 客户账单 表单 */
defineOptions({ name: 'CustomerBillForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  priceId: undefined,
  customerId: undefined,
  billDate: undefined,
  remark: undefined,
  orderNo: undefined,
  companyName: undefined,
  companyCode: undefined,
  containerType: undefined,
  containerCount: undefined,
  shipFee: undefined,
  dockFee: undefined,
  serviceFee: undefined,
  shipFeeUnit: 0,
  dockFeeUnit: 0,
  serviceFeeUnit: 0,
  totalFee: undefined,
  billStatus: undefined,
  payTime: undefined,
})
const formRules = reactive({
  customerId: [{ required: true, message: '客户不能为空', trigger: 'blur' }],
  priceId: [{ required: true, message: '船公司不能为空', trigger: 'blur' }],
  billDate: [{ required: true, message: '日期不能为空', trigger: 'blur' }],
  orderNo: [{ required: true, message: '订单号不能为空', trigger: 'blur' }],
  companyCode: [{ required: true, message: '船公司代码不能为空', trigger: 'blur' }],
  containerCount: [{ required: true, message: '柜型数量不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CustomerBillApi.getCustomerBill(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {

    formData.value.shipFee = parseFloat(formData.value.shipFeeUnit) * parseFloat(formData.value.containerCount) ;
    formData.value.dockFee = parseFloat(formData.value.dockFeeUnit) * parseFloat(formData.value.containerCount);
    formData.value.serviceFee = parseFloat(formData.value.serviceFeeUnit) * parseFloat(formData.value.containerCount);
    
    const data = formData.value as unknown as CustomerBillVO
    if (formType.value === 'create') {
      await CustomerBillApi.createCustomerBill(data)
      message.success(t('common.createSuccess'))
    } else {
      await CustomerBillApi.updateCustomerBill(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    priceId: undefined,
    customerId: undefined,
    billDate: undefined,
    remark: undefined,
    orderNo: undefined,
    companyName: undefined,
    companyCode: undefined,
    containerType: undefined,
    containerCount: undefined,
    shipFee: undefined,
    dockFee: undefined,
    serviceFee: undefined,
    shipFeeUnit: 0,
  dockFeeUnit: 0,
  serviceFeeUnit: 0,
    totalFee: undefined,
    billStatus: undefined,
    payTime: undefined,
  }
  formRef.value?.resetFields()
}


const options = ref<CustomerVO[]>([])
const value = ref<string[]>([])
const loading = ref(false)

var shipCompanyOptions = [];

var customer={};

var shipPrice = {};

const queryParams = reactive({
  pageNo: 1,
  pageSize: 50,
  customerName: "",
  companyCode: "",
})

const remoteMethod = async (query: string) => {

  loading.value = true
  try {
    queryParams.customerName= query;
    const data = await CustomerApi.getCustomerPage(queryParams)
    options.value = data.list
  } finally {
    loading.value = false
  }

}

const customerChange = (e) =>{
  console.log(e);
  customer = options.value.find((item) =>
        e == item.id
      );

    var containerCount=1;
    if(formData.value.containerCount!=undefined && formData.value.containerCount !=''){
        containerCount = formData.value.containerCount;
    }
    formData.value.serviceFeeUnit=customer.serviceFee ;

}


const searchShipCompany = async (query: string) => {

  loading.value = true
  try {
    queryParams.companyCode= query;
    const data = await PriceTemplateApi.getPriceTemplatePage(queryParams)
    shipCompanyOptions = data.list
  } finally {
    loading.value = false
  }

}

const shipCompanyChange = (e) =>{
  console.log(e);
   shipPrice = shipCompanyOptions.find((item) =>
        e == item.id
      );

    console.log(shipPrice);
    var containerCount=1;
    if(formData.value.containerCount!=undefined && formData.value.containerCount !=''){
        containerCount = formData.value.containerCount;
    }
    formData.value.shipFeeUnit=shipPrice.shipFee ;
    formData.value.dockFeeUnit=shipPrice.dockFee ;
    formData.value.companyCode=shipPrice.companyCode;
    formData.value.serviceFeeUnit=customer.serviceFee ;
    formData.value.containerType=shipPrice.containerType;
    formData.value.totalFee=(shipPrice.shipFee + shipPrice.dockFee + parseFloat(formData.value.serviceFeeUnit))*containerCount;

}

const containerCountInput = (e) =>{
    console.log(e);

     //formData.value.totalFee=(formData.value.shipFee+formData.value.dockFee+formData.value.serviceFee)*formData.value.containerCount;
    var containerCount=1;
    if(formData.value.containerCount!=undefined && formData.value.containerCount !=''){
        containerCount = formData.value.containerCount;
    }
    // formData.value.shipFeeUnit=shipPrice.shipFee ;
    // formData.value.dockFeeUnit=shipPrice.dockFee ;
    // formData.value.companyCode=shipPrice.companyCode;

    // formData.value.serviceFeeUnit=customer.serviceFee;

    console.log(formData.value);

    formData.value.containerType=shipPrice.containerType;
    formData.value.totalFee= (parseFloat(formData.value.shipFeeUnit)+parseFloat(formData.value.dockFeeUnit)+parseFloat(formData.value.serviceFeeUnit)) * containerCount;
}

</script>